package oakclub.model;

import com.google.gson.Gson;
import oakclub.entity.FriendEntity;
import oakclub.global.Json;
import oakclub.jooq.Tables;
import oakclub.jooq.tables.FriendData;
import oakclub.jooq.tables.FriendList;
import org.jooq.DSLContext;
import org.jooq.impl.DSL;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FriendModel extends BaseModel
{
    public void updateFriendlist(long userId, List<FriendEntity> friendlist) throws Exception
    {
        this.execute(new IExecute()
        {
            @Override
            public void execute(DSLContext context, Object... params) throws Exception
            {
                // params
                long userId = (long) params[0];
                List<FriendEntity> friendlist = (List<FriendEntity>) params[1];

                // friend ids & infos
                List<Long> friendIds = new ArrayList<Long>();
                Map<Long, Map<String, Object>> friendInfos = new HashMap<>();
                for(FriendEntity friend : friendlist)
                {
                    long friendId = friend.getId();
                    friendIds.add(friendId);

                    Map<String, Object> friendInfo = new HashMap<>();
                    friendInfo.put("fid", friendId);
                    friendInfo.put("name", friend.getName());
                    friendInfo.put("sex", friend.getGender().getId());
                    friendInfos.put(friendId, friendInfo);
                }

                // to json
                Gson jsonParser = Json.getParser();
                String jsonFriendIds = jsonParser.toJson(friendIds);
                String jsonFriendInfos = jsonParser.toJson(friendInfos);

                // table alias
                FriendList FL = Tables.FRIEND_LIST;
                FriendData FD = Tables.FRIEND_DATA;

                // update friend ids
                context
                    .insertInto(FL, FL.USER_ID, FL.FRIEND_ID)
                    .values(userId, jsonFriendIds)
                    .onDuplicateKeyUpdate()
                    .set(FL.FRIEND_ID, DSL.field("VALUES({0})", String.class, FL.FRIEND_ID))
                    .execute();

                // update friend infos
                context
                    .insertInto(FD, FD.USER_ID, FD.FRIEND_DATA_)
                    .values(userId, jsonFriendInfos)
                    .onDuplicateKeyUpdate()
                    .set(FD.FRIEND_DATA_, DSL.field("VALUES({0})", String.class, FD.FRIEND_DATA_))
                    .execute();
            }
        }, userId, friendlist);
    }
}
